package com.heitian.ssm.helper;

import com.heitian.ssm.controller.UserController;
import com.heitian.ssm.utils.CookieUtil;
import com.heitian.ssm.utils.SessionUtils;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.logging.Logger;

/**
 * created by mishuai on 2018/4/10
 */
public class CommInterceptor extends HandlerInterceptorAdapter{
    private org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger(CommInterceptor.class);
    public String defultLogin="/account/login";//默认登录页面
    public Map<String,String> defineUrls;//自定义的Url，自定义拦截后的处理页面。

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) throws Exception {

        HttpServletRequest httpRequest = request;
        String strBackUrl = "http://" + request.getServerName() // 服务器地址
                + ":" + request.getServerPort() // 端口号
                + httpRequest.getContextPath() // 项目名称
                + httpRequest.getServletPath() // 请求页面或其他地址
                + "?" + (httpRequest.getQueryString()); // 参数
        String url=httpRequest.getServletPath();
        //从cookie获取登录信息
        if(CookieUtil.getCookie(request, "userName")!=null)
        {
            return true;
        }
        else
        {
            if(defineUrls!=null&&defineUrls.size()>0)
            {
                if(defineUrls.containsKey(url))
                {
                    defultLogin=defineUrls.get(url).toString();
                }
            }
            log.info("Interceptor：跳转到login页面！"+defultLogin+"-----");
            response.sendRedirect(request.getContextPath()+defultLogin);
            return false;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request,
                           HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
    }

    public String getDefultLogin() {
        return defultLogin;
    }

    public void setDefultLogin(String defultLogin) {
        this.defultLogin = defultLogin;
    }

    public Map<String, String> getDefineUrls() {
        return defineUrls;
    }

    public void setDefineUrls(Map<String, String> defineUrls) {
        this.defineUrls = defineUrls;
    }
}
